package com.sk.sourcecircle.activity.find.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.jude.rollviewpager.hintview.IconHintView;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.home.activity.AblumDetailsActivity;
import com.sk.sourcecircle.activity.login.LoginActivity;
import com.sk.sourcecircle.adapter.AblumListAdapter;
import com.sk.sourcecircle.adapter.BannerAdapter;
import com.sk.sourcecircle.app.MyApplication;
import com.sk.sourcecircle.base.BaseFragment;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.callback.MyCallBack;
import com.sk.sourcecircle.dialog.CommentDialogFragment;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.AlbumListBean;
import com.sk.sourcecircle.entity.AlbumaBean;
import com.sk.sourcecircle.entity.HomeBannerBean;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.HttpAddress;
import com.sk.sourcecircle.utils.MD5;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.utils.UIUtils;
import com.sk.sourcecircle.view.EasyLoadingMoreView;
import com.sk.sourcecircle.view.FixedProportionViewPager;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.Unbinder;

/**
 * Created by sk on 2017/11/28.
 */

public class RoundAlbumFragment extends BaseFragment implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener, HandleDataCallBack, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.data_ryc)
    RecyclerView dataRyc;
    FixedProportionViewPager myPager;
    Unbinder unbinder;
    @BindView(R.id.swipe)
    SwipeRefreshLayout swipe;
    Unbinder unbinder1;

    private int page = 1;
    private AblumListAdapter adapter;
    private List<AlbumaBean> allDataList = new ArrayList<>();
    private boolean isLoadMore = false;
    private LoadingDialog loadingDialog;
    private int seletId;
    private int pos;
    private String comment = "";

    private MyCallBack myCallBack;
    private boolean isRefresh = false;

    public MyCallBack getMyCallBack() {
        return myCallBack;
    }

    public void setMyCallBack(MyCallBack myCallBack) {
        this.myCallBack = myCallBack;
    }

    @Override
    protected int getContentView() {
        return R.layout.fragment_round_album;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        swipe.setColorSchemeResources(R.color.home_checked_color, R.color.home_checked_color);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                doRefresh();
            }
        });

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);


        dataRyc.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new AblumListAdapter(R.layout.item_album, allDataList);
        dataRyc.setAdapter(adapter);
        View head = LayoutInflater.from(mContext).inflate(R.layout.item_head_banner, dataRyc, false);
        myPager = head.findViewById(R.id.my_pager);
        myPager.setHintView(new IconHintView(mContext, R.drawable.point_focus, R.drawable.point_normal, UIUtils.dip2px(mContext, 16)));
        adapter.addHeaderView(head);

        EasyLoadingMoreView loadMoreView = new EasyLoadingMoreView();
        adapter.setLoadMoreView(loadMoreView);
        View emptyView = getLayoutInflater().inflate(R.layout.empty_view, null);
        adapter.setEmptyView(emptyView);
        adapter.setOnItemClickListener(this);
        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this, dataRyc);

        getAlbum(page);
        AppApi.getRoundBanner(MyApplication.getInstance().getLat(), MyApplication.getInstance().getLng(), this, 20, getActivity());
    }

    public void getAlbum(final int page) {
        String path = HttpAddress.TestIp + HttpAddress.RoundAblum;
        RequestParams requestParams = new RequestParams(path);
        long timeStamp = System.currentTimeMillis();
        requestParams.addBodyParameter("timestamp", String.valueOf(timeStamp));
        requestParams.addBodyParameter("sign", MD5.md5(timeStamp + "_yuanquan"));
        requestParams.addBodyParameter("token", MyUtils.getToken(mContext));
        requestParams.addBodyParameter("page", String.valueOf(page));
        requestParams.addBodyParameter("lat", String.valueOf(MyApplication.getInstance().getLat()));
        requestParams.addBodyParameter("lng", String.valueOf(MyApplication.getInstance().getLng()));
        Log.v("getAlbum", requestParams.toString());
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                loadingDialog.cancelDialog();

                if (isRefresh) {
                    isRefresh = false;
                    swipe.setRefreshing(false);
                    SnackUtils.show(mRootView, "刷新成功！");
                }

                if (page == 1) {
                    allDataList.clear();
                }
                Log.v("getAlbum", result);
                AlbumListBean albumListBean = JSON.parseObject(result, AlbumListBean.class);
                List<AlbumaBean> dataBeanList = albumListBean.getData();
                allDataList.addAll(dataBeanList);
                if (dataBeanList.size() < 10) {
                    adapter.setEnableLoadMore(false);
                } else {
                    adapter.setEnableLoadMore(true);
                }
                if (isLoadMore) {
                    adapter.loadMoreComplete();
                    if (dataBeanList.size() == 0) {
                        adapter.loadMoreEnd();
                    }
                    isLoadMore = false;
                }
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.v("getAlbum", ex.toString());
                loadingDialog.cancelDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        pos = position;
        switch (view.getId()) {
            case R.id.comment:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent intent2 = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(intent2, 301);
                    return;
                }
                seletId = allDataList.get(position).getAlbum_id();
                CommentDialogFragment commentDialogFragment = new CommentDialogFragment();
                commentDialogFragment.setCallBack(RoundAlbumFragment.this);
                if (allDataList.get(position).getDetail().getIs_favorite() == 1) {
                    commentDialogFragment.setCollect(true);
                } else {
                    commentDialogFragment.setCollect(false);
                }
                commentDialogFragment.show(getActivity().getSupportFragmentManager(), "comment");
                break;
            case R.id.add_praise:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent intent2 = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(intent2, 301);
                    return;
                }
                loadingDialog.show();
                seletId = allDataList.get(position).getAlbum_id();
                AppApi.praiseAlbum(allDataList.get(position).getAlbum_id(), RoundAlbumFragment.this, 2, getActivity());
                break;
            case R.id.cancel_praise:
                break;
            case R.id.add_care:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent intent2 = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(intent2, 301);
                    return;
                }
                loadingDialog.show();
                AppApi.addFriend(allDataList.get(position).getUser_id(), RoundAlbumFragment.this, 4, getActivity());
                break;
            case R.id.cancel_care:
                break;
            case R.id.more:
                allDataList.get(position).setExpand(true);
                adapter.notifyItemChanged(position);
                break;
            case R.id.tv_delete:
                final int id = allDataList.get(position).getAlbum_id();
                TipDialogFragment tipDialogFragment = new TipDialogFragment();
                tipDialogFragment.setMyCallBack(new MyCallBack() {
                    @Override
                    public void releaseAlbum() {

                    }

                    @Override
                    public void joinGroup() {

                    }

                    @Override
                    public void takePhoto() {

                    }

                    @Override
                    public void choosePhoto() {

                    }

                    @Override
                    public void sure() {
                        loadingDialog.show();
                        AppApi.deleteAblumn(id, RoundAlbumFragment.this, 16, getActivity());
                    }

                    @Override
                    public void cancelOder(String string) {

                    }

                    @Override
                    public void chooseGroup(String id) {

                    }

                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void sendText(String comment) {

                    }
                });
                tipDialogFragment.setContent("确认删除该相册？");
                tipDialogFragment.show(getChildFragmentManager(), "delete");
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        isLoadMore = true;
        page++;
        getAlbum(page);
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 1:
                SnackUtils.show(mRootView, "评论发布成功！");
                AlbumaBean.DetailBean.ReplyBean replyBean = new AlbumaBean.DetailBean.ReplyBean();
                replyBean.setContent(comment);
                replyBean.setType("reply");
                replyBean.setNickname(MyUtils.getUser(mContext).getNickname());
                allDataList.get(pos).getDetail().getReply().add(replyBean);
                adapter.notifyItemChanged(pos);
                break;
            case 6:
                SnackUtils.show(mRootView, "相册收藏成功！");
                allDataList.get(pos).getDetail().setIs_favorite(1);
                adapter.notifyItemChanged(pos);
                break;
            case 2:
                SnackUtils.show(mRootView, "点赞成功！");
                AlbumaBean.DetailBean.ReplyBean praiseBean = new AlbumaBean.DetailBean.ReplyBean();
                praiseBean.setType("dig");
                praiseBean.setNickname(MyUtils.getUser(mContext).getNickname());
                allDataList.get(pos).getDetail().getReply().add(praiseBean);
                allDataList.get(pos).getDetail().setIs_dig(1);
                adapter.notifyItemChanged(pos);
                break;
            case 4:
                SnackUtils.show(mRootView, "请求发送成功，请等待回复！");
                break;
            case 20:
                HomeBannerBean homeBannerBean = JSON.parseObject(result, HomeBannerBean.class);
                List<HomeBannerBean.DataBean> bannerList = homeBannerBean.getData();
                BannerAdapter bannerAdapter = new BannerAdapter(bannerList, mContext);
                myPager.setAdapter(bannerAdapter);
                break;
            case 16:
                SnackUtils.show(mRootView, "相册删除成功！");
                allDataList.remove(pos);
                adapter.notifyItemRemoved(pos);
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();

    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();

    }

    @Override
    public void sendText(String comment) {
        super.sendText(comment);
        loadingDialog.show();
        this.comment = comment;
        AppApi.commentAlbum(seletId, comment, RoundAlbumFragment.this, 1, getActivity());
    }

    @Override
    public void sure() {
        super.sure();
        loadingDialog.show();
        AppApi.collectAlbum(seletId, RoundAlbumFragment.this, 6, getActivity());
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
            Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
            Intent intent2 = new Intent(mContext, LoginActivity.class);
            startActivityForResult(intent2, 301);
            return;
        }
        Intent intent = new Intent(mContext, AblumDetailsActivity.class);
        intent.putExtra("data", allDataList.get(position));
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            if (requestCode == 301) {
                loadingDialog.show();
                allDataList.clear();
                page = 1;
                getAlbum(page);
                AppApi.getRoundBanner(MyApplication.getInstance().getLat(), MyApplication.getInstance().getLng(), this, 20, getActivity());
            }
        }
    }

    public void doRefresh() {
        swipe.setRefreshing(true);
        isRefresh = true;
        page = 1;
        getAlbum(page);
        AppApi.getRoundBanner(MyApplication.getInstance().getLat(), MyApplication.getInstance().getLng(), this, 20, getActivity());
    }
}
